using System;
using System.IO;
using UnityEngine;
using UnityEngine.Recorder;

namespace UTJ.FrameCapturer.Recorders
{
	[Recorder(typeof(GIFRecorderSettings), "Video", "UTJ/GIF")]
	public class GIFRecorder : GenericRecorder<GIFRecorderSettings>
	{
		private fcAPI.fcGifContext m_ctx;

		private fcAPI.fcStream m_stream;

		public override bool BeginRecording(RecordingSession session)
		{
			if (!base.BeginRecording(session))
			{
				return false;
			}
			m_Settings.m_DestinationPath.CreateDirectory();
			return true;
		}

		public override void EndRecording(RecordingSession session)
		{
			m_ctx.Release();
			m_stream.Release();
			base.EndRecording(session);
		}

		public override void RecordFrame(RecordingSession session)
		{
			if (m_Inputs.Count != 1)
			{
				throw new Exception("Unsupported number of sources");
			}
			BaseRenderTextureInput baseRenderTextureInput = (BaseRenderTextureInput)m_Inputs[0];
			RenderTexture outputRT = baseRenderTextureInput.outputRT;
			if (!m_ctx)
			{
				fcAPI.fcGifConfig conf = m_Settings.m_GifEncoderSettings;
				conf.width = outputRT.width;
				conf.height = outputRT.height;
				m_ctx = fcAPI.fcGifCreateContext(ref conf);
				string path = m_Settings.m_BaseFileName.BuildFileName(session, base.recordedFramesCount, outputRT.width, outputRT.height, "gif");
				string path2 = Path.Combine(m_Settings.m_DestinationPath.GetFullPath(), path);
				m_stream = fcAPI.fcCreateFileStream(path2);
				fcAPI.fcGifAddOutputStream(m_ctx, m_stream);
			}
			fcAPI.fcLock(outputRT, TextureFormat.RGB24, delegate(byte[] data, fcAPI.fcPixelFormat fmt)
			{
				fcAPI.fcGifAddFramePixels(m_ctx, data, fmt, session.recorderTime);
			});
		}
	}
}
